package gui.VPOfOperations;

import entities.ProductionOrder;
import entities.RequestParameters;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Date;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.TitledBorder;
import javax.swing.event.TableModelEvent;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

import net.miginfocom.swing.MigLayout;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.labels.CategoryItemLabelGenerator;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.ValueMarker;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.time.Month;
import org.jfree.data.time.RegularTimePeriod;
import org.jfree.data.time.TimePeriod;
import org.jfree.data.time.TimePeriodValuesCollection;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeTableXYDataset;
import org.jfree.data.xy.XYDataset;
import org.jfree.ui.TextAnchor;

import table.model.EnvelopeTableModel;
import table.model.renderer.CrossTabRenderer;
import table.model.renderer.NumberRenderer;
import table.model.renderer.SimpleRenderer;
import utilities.PrintActionListener;

import javax.swing.ImageIcon;

import java.awt.SystemColor;
import java.awt.Font;

/**
 * @author Idan
 *Report GUI
 */
public class VPOfOperationsFailPercentageByTimeEngraveReport extends JPanel
{
	
	private JPanel mainPanel;
	private JScrollPane chartTableScroll;
	public DefaultTableModel model;
	private DefaultCategoryDataset dataset ;

	private VPOfOperationsTabbedPane tabbedpane;
	private JTable table;
	
	public VPOfOperationsFailPercentageByTimeEngraveReport(VPOfOperationsTabbedPane myTabbedPane, RequestParameters parameters) 
	{
		setBackground(new Color(173, 216, 230));
		this.tabbedpane = myTabbedPane;
		setLayout(new MigLayout("", "[][grow][]", "[][grow][][]"));
		
		mainPanel = new JPanel(){	@Override
			public void paintComponent(Graphics g) {
	        Graphics2D g2d = (Graphics2D) g;
	        Color color1 = getBackground();
	        Color color2 = color1.darker();
	        int w = getWidth();
	        int h = getHeight(); 
	        GradientPaint gp = new GradientPaint(
	                0, 0, color1,
	                0, h, color2);

	        g2d.setPaint(gp);
	        g2d.fillRect(0, 0, w, h);
	        }};
		mainPanel.setBackground(new Color(173, 216, 230));
		mainPanel.setBorder(new TitledBorder(null, "\u05D3\u05D5\u05D7 \u05E4\u05E1\u05D9\u05DC\u05D5\u05EA \u05E2\u05DC \u05E6\u05D9\u05E8 \u05D4\u05D6\u05DE\u05DF (\u05D9\u05D9\u05E6\u05D5\u05E8)   " + new Date(parameters.getStartTimestamp().getTime()) + " - " + new Date(parameters.getEndTimestamp().getTime()), TitledBorder.CENTER, TitledBorder.TOP, null, new Color(59, 59, 59)));
		add(mainPanel, "cell 1 1,growx,aligny center");
		mainPanel.setLayout(new MigLayout("", "[][grow]", "[][::200px][grow]"));
		
		JScrollPane scrollPane = new JScrollPane();
		mainPanel.add(scrollPane, "cell 1 1,alignx center,aligny center");
		
		table = new JTable();
		table.setFont(new Font("Tahoma", Font.PLAIN, 15));
		scrollPane.setViewportView(table);
		table.setModel(new DefaultTableModel(
			new Object[][] {
			},
			new String[] {
				"\u05D0\u05D7\u05D5\u05D6\u05D9 \u05E4\u05E1\u05D9\u05DC\u05D4 %", "\u05DE\u05E9\u05E4\u05D7\u05EA \u05DE\u05D5\u05E6\u05E8\u05D9\u05DD", "\u05EA\u05D0\u05E8\u05D9\u05DA"
			}
		) {
			boolean[] columnEditables = new boolean[] {
				true, false, false
			};
			public boolean isCellEditable(int row, int column) {
				return columnEditables[column];
			}
		});
		table.getColumnModel().getColumn(1).setPreferredWidth(117);
		table.setBorder(new TitledBorder(null, "", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		
		
	
		
		JButton closeButton = new JButton("סגור דוח");
		closeButton.setFont(new Font("Tahoma", Font.PLAIN, 13));
		closeButton.setIcon(new ImageIcon(VPOfOperationsFailPercentageByTimeEngraveReport.class.getResource("/graphics/back.png")));
		closeButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0)
			{
				// get tab index
				tabbedpane.remove(tabbedpane.getSelectedIndex());
				// remove tab
			}
		});
		add(closeButton, "flowx,cell 1 2,alignx center");
		
		JLabel lblNewLabel = new JLabel("               ");
		add(lblNewLabel, "cell 1 2");
		
		JButton printButton = new JButton("יצא לאקסל");
		printButton.setFont(new Font("Tahoma", Font.PLAIN, 13));
		printButton.setIcon(new ImageIcon(VPOfOperationsFailPercentageByTimeEngraveReport.class.getResource("/graphics/excel.png")));
		printButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) 
			{
//JTable table = utilities.Services.parsePivotTableToJTrable(myTable);
				
				ArrayList<Object> result = utilities.Services.exportToExcel(table);
				if (result.get(0).equals(true))
				{
					// confirm
					JOptionPane.showMessageDialog(mainPanel,
							result.get(1).toString() + " :הדוח נשמר " ,"אישור",JOptionPane.INFORMATION_MESSAGE);
				}
				else
				{
					// error
					JOptionPane.showMessageDialog(mainPanel,
						    "לא ניתן לשמור את הדוח.","שגיאה",JOptionPane.ERROR_MESSAGE);
				}
				//new Thread(new PrintActionListener(mainPanel)).start();
			}		
		});
		add(printButton, "cell 1 2,alignx center");
		
		
		  
	}
	
	public void setVariables(ArrayList<Object> response) 
	{
		// index 0 is the flag
		// index 1 is the counter
		// index 2 and onwards is the data

		
		model = (DefaultTableModel) table.getModel();
		
	//	int columnCount = 2;
		int rowCount = (int) response.get(1);
		//String family = response.get(2).toString();
		 

		
	//	model.addColumn("סיבת פסילה", columnData);	
		
		// Object[] columnData = null;
		
		
		
		 TimeTableXYDataset dataset = new TimeTableXYDataset();
		
		 for (int i=1; i<=((int)response.get(1));i++)
	     {
			 ProductionOrder order = (ProductionOrder)response.get(i+1);
			 model.addRow(new Object[]{order.getFailsPercentage()*100,order.getProductFamily(),order.getDateAsMonthYear()});

			 Month date = null;
			try
			{
				date = new Month(new Date( new SimpleDateFormat("MM/yyyy").parse(order.getDateAsMonthYear()).getTime()));
			}
			catch (ParseException e)
			{
			//	System.out.println("Coundn't parse the date");
				// TODO Auto-generated catch block
				//e.printStackTrace();
			}
			 dataset.add(date, order.getFailsPercentage(), order.getProductFamily() );
			 
	     }
		 
	 


		        // create Chart
		        
		 JFreeChart chart = ChartFactory.createTimeSeriesChart(
				 ((TitledBorder)mainPanel.getBorder()).getTitle(),
				 "תאריך",
				 "אחוז פסילה",
				 dataset);
		      
		      //  JFreeChart chart = ChartFactory.createBarChart(
		       /* JFreeChart chart = ChartFactory.createStackedBarChart3D(
		        		((TitledBorder)mainPanel.getBorder()).getTitle(), // chart title
		        		"קו ייצור", // domain axis label
		        		"פסילות", // range axis label
		        		dataset, // data
		        		PlotOrientation.VERTICAL, // orientation
		        		true, // include legend
		        		true, // tooltips?
		        		false // URLs?
		        		);

		        */
		  
		 	final XYPlot plot = chart.getXYPlot();
		 	XYItemRenderer renderer = plot.getRenderer();
		 	int numberOfSerieses = dataset.getSeriesCount();
		 	for (int i =0 ; i<numberOfSerieses ; i++)
		 	{
		 		renderer.setSeriesStroke(i, new BasicStroke(2.0f));
		 	}
		 	
		   
		       // final CategoryPlot plot = (CategoryPlot) chart.getPlot();
		      //  plot.setRenderer(new StackedBarRenderer3D(true));
		 	//	BarRenderer renderer =  (BarRenderer) plot.getRenderer();
		      //  DecimalFormat format = new DecimalFormat("##.##");
		     //   renderer.setBaseItemLabelGenerator((CategoryItemLabelGenerator) new StandardCategoryItemLabelGenerator("{2}",format));
		        renderer.setPositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.TOP_CENTER));
		        renderer.setItemLabelsVisible(true);
		        
		      
		    //    CategoryAxis xAxis = (CategoryAxis)plot.getDomainAxis();
		    //    xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);
		        
//		        renderer.setSeriesItemLabelsVisible(0, true);

		        //renderer.
		        // renderer.setItemMargin(0.0);
		        
		        
		        ChartPanel chartPanel = new ChartPanel(chart, false);
		        chartPanel.setMouseWheelEnabled(true);
		        chartPanel.setHorizontalAxisTrace(true);
		        chartPanel.setVerticalAxisTrace(true);
		      //  chartPanel.setPreferredSize(new Dimension(500, 270));
		        
		        chartTableScroll = new JScrollPane(chartPanel);
		        mainPanel.add(chartTableScroll, "cell 1 2,grow");
		       // mainPanel.add(chartPanel, "cell 1 2,grow");
		       // chartPanel.setVisible(true);
		        

		
		
	}
	
	@Override
	public void paintComponent(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    Color color1 = getBackground();
    Color color2 = color1.darker();
    int w = getWidth();
    int h = getHeight(); 
    GradientPaint gp = new GradientPaint(
            0, 0, color1,
            0, h, color2);

    g2d.setPaint(gp);
    g2d.fillRect(0, 0, w, h);
    }
}
